use std::io;
use std::error::Error;
use std::fmt;

// 自定义错误类型，实现 std::error::Error 和 std::fmt::Display 特征
#[derive(Debug)]
struct ConversionError;

impl Error for ConversionError {}

impl fmt::Display for ConversionError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Conversion error")
    }
}

pub fn convert_time_to_milliseconds(time_str: &str) -> io::Result<u32> {
    let time_parts: Vec<&str> = time_str.split(':').collect();
    if time_parts.len() != 3 {
        return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid time format"));
    }

    let hours: u32 = time_parts[0].parse().map_err(|_e| io::Error::new(io::ErrorKind::InvalidData, ConversionError))?;
    let minutes: u32 = time_parts[1].parse().map_err(|_e| io::Error::new(io::ErrorKind::InvalidData, ConversionError))?;

    let seconds_and_milliseconds: Vec<&str> = time_parts[2].split(',').collect();
    if seconds_and_milliseconds.len() != 2 {
        return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid time format"));
    }

    let seconds: u32 = seconds_and_milliseconds[0].parse().map_err(|_e| io::Error::new(io::ErrorKind::InvalidData, ConversionError))?;
    let milliseconds: u32 = seconds_and_milliseconds[1].parse().map_err(|_e| io::Error::new(io::ErrorKind::InvalidData, ConversionError))?;

    let total_milliseconds = hours * 3600000 + minutes * 60000 + seconds * 1000 + milliseconds;

    Ok(total_milliseconds)
}
